package work.soho.proxy.component.impl;

import work.soho.proxy.ConfigManage;
import work.soho.proxy.ProxyApplication;
import work.soho.proxy.aliyun.parts.*;
import work.soho.proxy.component.IComponent;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

public class ProxySocket5Impl implements IComponent {
    private ConfigManage configManage;

    /**
     * proxy，register 检查线程
     */
    private Thread checkThread = null;

    public ConfigManage getConfigManage() {
        return configManage;
    }

    public void setConfigManage(ConfigManage configManage) {
        this.configManage = configManage;
    }

    public ProxySocket5Impl() {
        setConfigManage(ProxyApplication.configManage);
    }

    /**
     * 启动socket5代理
     *
     * @return
     */
    @Override
    public boolean  start() {
        ArrayList<String> list = new ArrayList<>();
        list.add(ImportKeyPairPart.class.getName()); //导入密钥对
        list.add(VpcPart.class.getName()); //虚拟网络
        list.add(SwitchPart.class.getName()); //交换机
        list.add(SecurityGroupPart.class.getName()); //安全组
        list.add(ServerInstancePart.class.getName()); //服务器实例

        synchronized(this) {
            int i=0;
            do {
                System.out.println("尝试启动：" + i);
                try {
                    PartsManage.check(list);
//                    if(isPortUsed()) {
//                        System.out.println("启动成功！");
//                        return true;
//                    } else {
//                        System.out.println("执行代理操作");
//                        PartsManage.startSocket5();
//                    }
                    Thread.sleep(3 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } while (i++ <100);
        }
        return false;
    }

    @Override
    public boolean stop() {
        //nothing todo
        return false;
    }

    @Override
    public boolean unRegister() {
        return false;
    }

    /**
     * 检查守护端口是否在使用
     *
     * @return
     */
    public boolean isPortUsed() {
        try {
            Socket socket = new Socket("127.0.0.1", Integer.parseInt(configManage.getPartsConfigure().getProxyPort()));
            socket.close();
            return true;
        } catch (IOException e) {
            //nothing todo
        }
        return false;
    }
}
